/// @tags:
#include <cstdio>
#include <functional>
#include <iostream>
#include <numeric>

using std::cin, std::cout, std::endl;

namespace BlueQuantum {

constexpr int maxn = 1e5 + 2, mod = 998244353;

int ecnt;
int heads[maxn];

struct Edge {
  int v, nxt;
} e[maxn * 2];

inline void add(int u, int v) {
  e[ecnt].v = v, e[ecnt].nxt = heads[u], heads[u] = ecnt++;
}

bool vis[maxn];
int a[maxn], b[maxn];

bool dfs(int u, int f) {
  bool res = false;
  vis[u] = true;
  for (int i = heads[u]; i != -1; i = e[i].nxt) {
    int v = e[i].v;
    if (i == (f ^ 1)) continue;
    if (vis[v]) {
      res = true;
    } else {
      res |= dfs(v, i);
    }
  }
  return res;
}

int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    ecnt = 0;
    for (int i = 1; i <= n; ++i) {
      vis[i] = false;
      heads[i] = -1;
    }
    for (int i = 1; i <= n; ++i) {
      cin >> a[i];
    }
    for (int i = 1; i <= n; ++i) {
      cin >> b[i];
    }
    long long ans = 1;
    int cnt = 0;
    for (int i = 1; i <= n; ++i) {
      if (a[i] == b[i]) {
        ans *= n;
        ans %= mod;
        ++cnt;
      }
      add(a[i], b[i]);
      add(b[i], a[i]);
    }
    for (int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        if (dfs(i, -1)) {
          ans *= 2;
          ans %= mod;
        } else {
          ans = 0;
        }
      }
    }
    for (int i = 1; i <= cnt; ++i) ans *= 499122177, ans %= mod;
    cout << ans << '\n';
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("D. Koxia and Game.in", "r", stdin);
  freopen("D. Koxia and Game.out", "w", stdout);
#endif
#endif

  std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
